<template>
  <el-cascader
    ref="cascaderRef"
    v-model="selectedValue"
    :disabled="disabled"
    :multiple="multiple"
    :options="cascaderOptions.dataList"
    :placeholder="placeholder"
    :props="cascaderOptions.props"
    :style="width > 0 ? state.style : state.fullStyle"
    @change="handleChange"
  />
</template>
<script setup name="AreaPicker" lang="ts">
import { queryList } from "@/api/admin/system/area";
import { BasicCascaderProps, useCascader } from "@/hooks/cascader";

const props = defineProps({
  // 文字提示
  placeholder: {
    type: String,
    default: function () {
      return "请选择";
    }
  },
  width: {
    type: Number,
    default: function () {
      return 0;
    }
  },
  disabled: {
    type: Boolean,
    default: function () {
      return false;
    }
  },
  multiple: {
    type: Boolean,
    default: function () {
      return false;
    }
  }
});
const emits = defineEmits(["change"]);
const defaultValue = defineModel<string>("defaultValue");
const selectedValue = ref<string | number | string[] | number[] | any>();
const cascaderRef = ref(null);

const state = reactive({
  style: { width: `${props.width}px` },
  fullStyle: { width: `100%` }
});

onMounted(() => {
  if (defaultValue) {
    if (props.multiple) {
      selectedValue.value = defaultValue.value.split(",");
    } else {
      selectedValue.value = defaultValue.value;
    }
  }
});

const cascaderOptions = reactive<BasicCascaderProps>({
  queryForm: { pid: "0" },
  props: {
    checkStrictly: true,
    multiple: props.multiple,
    emitPath: false,
    label: "areaName",
    value: "id",
    leaf: "leaf",
    lazy: true
  },
  queryFunction: queryList
});

const { queryCascaderData } = useCascader(cascaderOptions);

const getValue = () => {
  return selectedValue.value;
};

const handleChange = val => {
  selectedValue.value = val;
  const nodes = cascaderRef.value.getCheckedNodes();
  emits("change", val, nodes);
};

// 重新加载数据，供父页面调用
const reload = () => {
  cascaderOptions.queryForm.level = 1;
  queryCascaderData();
};

defineExpose({
  reload,
  getValue
});
</script>

<style lang="scss" scoped>
.el-input__inner {
  width: 100px;
}
</style>
